const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
/**
 * @type {import('webpack').Configuration}
 */
module.exports = (env, argv) => {
  const config = {
    entry: './src/main-prod.js',
    output: {
      path: path.join(__dirname, 'dist-prod'),
      filename: 'js/bundle.js',
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          use: {
            loader: 'babel-loader',
            options: { presets: ['@babel/preset-env'] },
          },
        },
        { test: /\.css$/, use: ['style-loader', 'css-loader'] },
        {
          test: /\.(png|jpg)$/,
          use: { loader: 'url-loader', options: { limit: 10240 } },
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: 'index-prod.html',
      }),
    ],
  };

  if (env === 'production') {
    (config.mode = 'production'), (config.devtool = false);
    config.plugins = [
      ...config.plugins,
      new CleanWebpackPlugin(),
      new CopyWebpackPlugin({
        patterns: [{ from: 'public', to: '.' }],
      }),
    ];
  }

  return config;
};

// webpack.config.common.js
const commonConfig = {
  entry: './src/main-prod.js',
  output: {
    path: path.join(__dirname, 'dist-prod'),
    filename: 'js/bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: { presets: ['@babel/preset-env'] },
        },
      },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      {
        test: /\.(png|jpg)$/,
        use: { loader: 'url-loader', options: { limit: 10240 } },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'index-prod.html',
    }),
  ],
};

// webpack.config.prod.js

merge(commonConfig, {
  mode: 'production',
  // 集中配置webpack的相关优化
  optimization: {
    // 标记哪些是枯树枝
    usedExports: true,
    // 将标记的枯树枝摇出去
    minimize: true,
    // 合并模块到一个函数 scope hoisting
    concatenateModules: true,
    // 开启副作用，在package.json里面配置的sideEffects，可以告诉webpack依赖的包是否有副作用
    // 允许通过配置的方式去标识代码是否有副作用
    // 一般用于npm 包标记是否有副作用
    sideEffects: true,
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [{ from: 'public', to: '.' }],
    }),
    // 自动注入process.env.NODE_ENV
    new webpack.DefinePlugin({
      // 这儿传递的是一段js代码。
      API_BASE_URL: '"http://api.example.com"',
    }),
  ],
});
